//这是要遍历时间轴的数据
let searchData = localStorage.getItem('taosha_sk');
searchData = JSON.parse(searchData) || [];

console.log(searchData.length);
if (searchData.length > 0) {
  $('.j-delete-all-history').css('visibility', 'visible');
}

let aleadyExistDates = [];

var dimeAxis = searchData.map(v => {
  let time = +v.time;
  let date = new Date(time);
  date = dateFormat('YYYY-mm-dd HH:MM', date);
  let title = v.keyword;
  return {time, date, title};
});

aleadyExistDates.length = 0;


$(function () {
  $.each(dimeAxis, function (i, e) {
    var html = '<li class="time-axis-item">' +
      '<div class="time-axis-date">' + e.date + '<span></span></div>' +
      '<div class="time-axis-title"><a class="time-axis-title-a" time=' + e.time + ' target="_blank" href="https://taosha.club/search?q=' + e.title + '">' + e.title + '</a><i time=' + e.time + ' class="fa fa-times j-delete-history" aria-hidden="true"></i></div>' +
      '</li>';
    $('.time-axis').append(html);
  });

  $('.j-delete-all-history').click(function () {
    let r = confirm('你确定要删除全部历史记录吗？');
    if (r) {
      localStorage.removeItem('taosha_sk');
      $('.time-axis-item').remove();
      $('.j-delete-all-history').css('visibility', 'hidden');
      $('.search__autocomplete').html(null).css('visibility', 'hidden');
    }
  });

  $('.time-axis-title-a').click(function (evt) {
    const localStorageKey = 'taosha_sk';

    let keyword = $(evt.target).text();
    let time = $(evt.target).attr('time');
    let value = {keyword, time};
    let list = JSON.parse(localStorage.getItem(localStorageKey)) || [];
    let index = list.findIndex(function (v) {
      return v.time == time;
    });

    list.splice(index, 1);
    list.unshift(value);
    localStorage.setItem(localStorageKey, JSON.stringify(list));
  });

  $('.j-delete-history').click(function (evt) {
    $(evt.target).closest('.time-axis-item').remove();

    const localStorageKey = 'taosha_sk';
    let time = $(evt.target).attr('time');
    let list = JSON.parse(localStorage.getItem(localStorageKey)) || [];
    let index = list.findIndex(function (v) {
      return v.time == time;
    });

    list.splice(index, 1);
    localStorage.setItem(localStorageKey, JSON.stringify(list));

    if (list.length == 0) {
      $('.j-delete-all-history').css('visibility', 'hidden');
    }
  });
});

function dateFormat(fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
    }
  }
  return fmt;
}
